package com.eesujie.xcs.util;

import com.eesujie.xcs.common.BusinessException;
import org.springframework.beans.BeanUtils;

public class PojoUtils {
    public static <PO, VO> VO parseVO(PO po) {
        try {
            var replace = po.getClass().getName()
                    .replace(".po.", ".vo.");
            int index = replace.lastIndexOf("PO");
            var voClass = Class.forName(
                replace.substring(0, index) + "VO" + replace.substring(index + "PO".length())
            );
            var vo = voClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(po, vo, voClass);
            return (VO)vo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(po.getClass().getName() + "can't find vo");
        }
    }

    public static <DTO, PO> PO parsePO(DTO dto) {
        try {
            var replace = dto.getClass().getName()
                    .replace(".dto.", ".po.");
            int index = replace.lastIndexOf("DTO");
            var voClass = Class.forName(
                    replace.substring(0, index) + "PO" + replace.substring(index + "DTO".length())
            );
            var po = voClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(dto, po, voClass);
            return (PO)po;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(dto.getClass().getName() + "can't find po");
        }

    }
}
